create proc dbo.p_ScanStatus(
					@DatabaseID bigint,
					@ScanTypeID bigint,
					@ObjectType varchar(50),
					@ObjectID bigint=null) as

declare @ScanInProgressStart datetime,
		@LastScanComplete datetime

if @ObjectID is null
select
	@ScanInProgressStart=
	(select
		max(a.[scanstart])
	from
		scanhistory a
	where
		a.[databaseid]=@DatabaseID
		and a.[objecttype]=@ObjectType
		and a.[scancomplete] is null
	),
	@LastScanComplete=
	(select
		max(a.[scancomplete])
	from
		scanhistory a
	where
		a.[databaseid]=@DatabaseID
		and a.[objecttype]=@ObjectType
		and not a.[scancomplete] is null
	) 
else
select
	@ScanInProgressStart=
	(select
		max(a.[scanstart])
	from
		scanhistory a
	where
		a.[databaseid]=@DatabaseID
		and a.[objecttype]=@ObjectType
		and a.[objectid]=@ObjectID
		and a.[scancomplete] is null
	),
	@LastScanComplete=
	(select
		max(a.[scancomplete])
	from
		scanhistory a
	where
		a.[databaseid]=@DatabaseID
		and a.[objecttype]=@ObjectType
		and a.[objectid]=@ObjectID
		and not a.[scancomplete] is null
	) 
select 
	case 
		when @ScanTypeID=1 and datediff(minute,@ScanInProgressStart,current_timestamp)>
				(select convert(int,n.[value]) from [Configuration] n where n.[name]='SCHEMA_SCAN_TIMEOUT_PERIOD')
			then null

		when @ScanTypeID=2 and datediff(minute,@ScanInProgressStart,current_timestamp)>
				(select convert(int,n.[value]) from [Configuration] n where n.[name]='SIZE_SCAN_TIMEOUT_PERIOD')
			then null

		when @ScanTypeID=3 and datediff(minute,@ScanInProgressStart,current_timestamp)>
				(select convert(int,n.[value]) from [Configuration] n where n.[name]='BLOCK_SCAN_TIMEOUT_PERIOD')
			then null

		when @ScanTypeID=4 and datediff(minute,@ScanInProgressStart,current_timestamp)>
				(select convert(int,n.[value]) from [Configuration] n where n.[name]='CONNECTION_SCAN_TIMEOUT_PERIOD')
			then null

		when @ScanTypeID=5 and datediff(minute,@ScanInProgressStart,current_timestamp)>
				(select convert(int,n.[value]) from [Configuration] n where n.[name]='WAITSTATE_SCAN_TIMEOUT_PERIOD')
			then null

		else @ScanInProgressStart
	end 'ScanInProgressStart',
	@LastScanComplete